﻿using System;
using Enyim.Caching;
using Ayatta.Contract;
using Web.My.Models;
using System.Web.Mvc;
using Web.Core.Security;
using Web.Core.Extensions;
using Ayatta.Contract.Domain;
using Ayatta.Common.Extension;

namespace Web.My.Controllers
{
    public class SecurityController : BaseController
    {

        public SecurityController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {
        }

        public ActionResult Index()
        {
            //var model = new SecurityControllerModel.Index();
            var identity = User.Identity.Identity();
            var model = Passport.Value.UserGet(identity.Id);
            return View(model);
        }

        #region 密码更新
        public ActionResult Password()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Password(string oldPassword, string newPassword)
        {
            var identity = User.Identity.Identity();
            var result = new MagicKit<int>();

            if (string.IsNullOrEmpty(oldPassword))
            {
                result.Data = 0;
                result.Message = "请输入原密码！";
                return Json(result);
            }
            if (!newPassword.IsPassword())
            {
                result.Data = 1;
                result.Message = "6-12位，至少两个字母、两个数字、一个特殊字符！";
                return Json(result);
            }

            var user = Passport.Value.UserSignIn(User.Identity.Name, oldPassword);
            if (user != null)
            {
                var password = (newPassword.HashPassword() + PasswordSalt).HashPassword();
                if (password == user.Password)
                {
                    result.Data = 1;
                    result.Message = "新密码不能与原密码一样！";
                }
                else
                {
                    result.Status = Passport.Value.UserPasswordUpdate(identity.Id, password);
                    if (!result.Status)
                    {
                        result.Message = "更新密码失败！";
                    }
                }
            }
            else
            {
                result.Data = 0;
                result.Message = "请输入正确的原密码！";
            }
            return Json(result);
        }

        #endregion

        #region 实名认证

        public ActionResult Authenticate()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Authenticate(string code, string name, Gender gender, DateTime birthday)
        {
            return View();
        }
        #endregion

        #region 邮箱绑定
        /// <summary>
        /// 邮箱绑定
        /// </summary>
        /// <returns></returns>
        public ActionResult EmailBind()
        {
            return PartialView();
        }

        /// <summary>
        /// 邮箱绑定
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EmailBind(string email)
        {
            var result = new MagicKit<string>();
            var identity = User.Identity.Identity();
            if (!email.IsEmail())
            {
                result.Message = "请输入正确的电子邮箱地址！";
                return Json(result);
            }

            var exist = Passport.Value.UserExist(email);
            //exist.Data 为用户Id
            //exist.Message 为用户Name

            if (!exist.Status)
            {
                var auth = new AuthEmail();
                var id = Guid.NewGuid().ToString().ToUpper();

                auth.Id = id;
                auth.UserId = identity.Id;
                auth.Group = 1;
                auth.Email = email;
                auth.Status = false;
                auth.CreatedBy = User.Identity.Name;
                auth.CreatedOn = DateTime.Now;

                var status = Extra.Value.AuthEmailCreate(auth);
                if (status)
                {
                    result.Status = true;
                    // todo 发送邮箱绑定邮件
                }
                else
                {
                    result.Message = "发送邮件失败！";
                }
            }
            else
            {
                result.Message = "该邮箱已被使用，请换一个！";
            }

            return Json(result);
        }

        /// <summary>
        /// 验证邮箱绑定
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult EmailBindValidate(string param)
        {
            var result = new MagicKit<string>();
            var identity = User.Identity.Identity();

            var auth = Extra.Value.AuthEmailGet(param, 1);
            if (auth != null && !auth.Status)
            {
                var status = Passport.Value.UserEmailBind(identity.Id, auth.Email);
                if (status)
                {
                    result.Status = true;
                    Extra.Value.AuthEmailStatusUpdate(param);
                }
                else
                {
                    result.Message = "绑定邮箱失败！";
                }
            }
            else
            {
                result.Message = "链接无效或已过期，请重新获取有效链接！";
            }

            return Json(result);
        }

        #endregion

        #region 手机绑定
        /// <summary>
        /// 手机绑定
        /// </summary>
        /// <returns></returns>
        public ActionResult MobileBind()
        {
            return PartialView();
        }

        /// <summary>
        /// 手机绑定
        /// </summary>
        /// <param name="mobile">手机号码</param>
        /// <param name="authId">短信验证Id</param>
        /// <param name="authCode">短信验证码 </param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MobileBind(string mobile, string authId, string authCode)
        {
            var result = new MagicKit<string>();
            var identity = User.Identity.Identity();
            if (!mobile.IsMobile())
            {
                result.Message = "请输入正确的手机号码！";
                return Json(result);
            }

            var auth = Extra.Value.AuthSmsGet(authId, mobile, 1, authCode);
            if (auth == null || auth.Status || mobile != auth.Mobile)
            {
                result.Message = "短信验证码不正确或已过期！";
                return Json(result);
            }
            var exist = Passport.Value.UserExist(mobile);
            if (!exist.Status)
            {
                var status = Passport.Value.UserMobileBind(identity.Id, auth.Mobile);
                if (status)
                {
                    result.Status = true;
                    Extra.Value.AuthSmsStatusUpdate(authId);
                }
                else
                {
                    result.Message = "绑定手机失败！";
                }
            }
            else
            {
                result.Message = "该手机号码已绑定其它帐号，请换个手机号码！";
            }
            return Json(result);
        }

        #endregion
    }
}
